package com.authine.cloudpivot.ext.controller.materials;

import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkItemModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkflowInstanceModel;
import com.authine.cloudpivot.engine.enums.status.SequenceStatus;
import com.authine.cloudpivot.ext.Utils.CustomSchemaCode;
import com.authine.cloudpivot.ext.Utils.Utils;
import com.authine.cloudpivot.ext.service.CloudSqlService;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @author fengjie
 * @version 1.0.0
 * @ClassName CompanyMaterialsController
 * @Description 公司物料信息记录
 * @createTime 2023/2/9 10:23
 */
@RestController
@RequestMapping("/public/companyMaterials")
@Slf4j
public class CompanyMaterialsController extends BaseController {
    @Autowired
    CloudSqlService sqlService;

    /**
     * 【公司物料记录 基础信息】审批完成后，数据同步到【公司物料信息记录 基础表】
     */
    @RequestMapping("finish")
    public void finish(String bizId) {
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.COMPANY_MATERIALS_BA, bizId);
        //相关档案明细表
        List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get(CustomSchemaCode.COMPANY_MATERIALS_DETAIL_BA);
//        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        String approval = getFileBaseInfoWorkFlowApproval(bizObject);
        for (Map<String, Object> map : list) {
            try {
                //将子表中数据处理，随后更新至【公司物料信息记录 基础表】
//                Map<String, Object> data = fileInfoBaseMap(map, now, approval);
                Map<String, Object> data = Utils.fileInfoBaseMap(map, approval);

                //判断是否已存在
                String id = existsBizObject(data);
                if (StringUtils.isNotEmpty(id)) {
                    data.put("id", id);
                }
                BizObjectCreatedModel model = new BizObjectCreatedModel(CustomSchemaCode.COMPANY_MATERIALS, data, false);
                model.setSequenceStatus(SequenceStatus.COMPLETED.name());
                model.put("CompanyPersonName",data.get("companyDutyPerson"));
                id = getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
                log.info("公司物料信息记录 基础信息数据更新成功");

                callProcess(id);
            } catch (Exception e) {
                log.info("公司物料信息记录 基础信息数据维护失败或存储过程调用失败，报错信息：{}", e.getMessage());
                log.info("公司物料信息记录 基础信息操作失败 公司编码={}，物料编码={}", map.get("companyNumber"), map.get("fullCodeNumber"));
            }
        }
    }

    /**
     * 调用存储过程
     * -----公司物料信息记录
     * exec    SyncComMatInfo
     *
     * @Comid nvarchar(100),            ----公司ID
     * @Code nvarchar(100),            ----物料编码
     * @comdeptid nvarchar(100),            ----公司主责部门ID
     * @PosACode nvarchar(50),            ----岗A代码
     * @PosBCode nvarchar(50),            ----岗B代码
     * @Person nvarchar(50),            ----主责人
     * @Auditor nvarchar(50)            ----审批人 02.0100 张三
     */
    private void callProcess(String bizId) {

        if (StringUtils.isEmpty(bizId)) {
            return;
        }
        //编写sql
        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.COMPANY_MATERIALS);
        StringBuilder sql = new StringBuilder("SELECT * from ")
                .append(tableName).append(" where id ='")
                .append(bizId).append("';");
        //查询到入参
        Map<String, Object> map = sqlService.getMap(sql.toString());

        log.info("入参map={}", map);

        //调用存储过程
        String company = MapUtils.getString(map, "company", "");
        String fullCodeNumber = MapUtils.getString(map, "fullCodeNumber", "");
        String responsibleDeptFid = MapUtils.getString(map, "companyDutyDeptFid", "");
        String companyPostANumber = MapUtils.getString(map, "companyPostANumber", "");
        String companyPostBNumber = MapUtils.getString(map, "companyPostBNumber", "");
        String responsiblePersonName = MapUtils.getString(map, "CompanyPersonName", "");
        String approver = MapUtils.getString(map, "approver", "");//审批人

        String execSql = String.format("exec [HG_LINK].[hg].[dbo].SyncComMatInfo '%s','%s','%s','%s','%s','%s','%s'",
                company, fullCodeNumber, responsibleDeptFid, companyPostANumber, companyPostBNumber, responsiblePersonName, approver);

        log.info("\n==========准备调用[SyncComMatInfo]公司物料信息记录存储过程:{}", execSql);
        sqlService.execute(CloudSqlService.htEas, execSql);
        log.info("\n=============[SyncComMatInfo]公司物料信息记录存储过程执行完成");

    }

    /**
     * 更新公司物料信息-采购信息
     */
    @RequestMapping("updateCompanyMaterialsPurchase")
    public void updateCompanyMaterialsPurchase(String bizId) {
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.COMPANY_MATERIALS_PU, bizId);

        //相关档案明细表
        List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get(CustomSchemaCode.COMPANY_MATERIALS_DETAIL_PU);

        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        String approval = getFileBaseInfoWorkFlowApproval(bizObject);

        for (Map<String, Object> map : list) {
            try {
                //将子表中数据处理，随后更新至【公司物料信息记录 基础表】
                Map<String, Object> data = Utils.fileInfoBaseMap(map, approval);
                //判断是否已存在
                String id = existsBizObject(map);
                //采购时子表数据存在，做更新
                data.put("id", id);
                BizObjectCreatedModel model = new BizObjectCreatedModel(CustomSchemaCode.COMPANY_MATERIALS, data, false);
                model.setSequenceStatus(SequenceStatus.COMPLETED.name());
                id = getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
                log.info("公司物料信息记录 采购信息数据维护成功");

                callProcessToPurchase(id);
            } catch (Exception e) {
                log.info("公司物料信息记录 采购信息维护失败，报错信息：{}", e.getMessage());
                log.info("公司物料信息记录 采购信息操作失败 公司编码={}，物料编码={}", map.get("companyNumber"), map.get("fullCodeNumber"));
            }
        }
    }

    /**
     * -----公司物料信息记录 采购信息
     * exec     SyncComMatPurchaseInfo
     *
     * @comid nvarchar(100),            ----公司id
     * @Code nvarchar(100),            ----物料代码
     * @Purarch nvarchar(100),            ----公司采购
     * @PurPosCode nvarchar(100),        ----公司采购岗代码
     * @MainSupplierID nvarchar(100),    ----主供应商ID
     * @PurUnitName nvarchar(100),        ----采购计量单位名称
     * @PurMode nvarchar(50),        ----采购方式  	 'group' then '集团'    'company'  '公司'   else  '' end  as 采购方式,
     * @PurLvl nvarchar(50),        ----采购等级  '1'  I级   '2'  Ⅱ级  '3'  Ⅲ级    '0'  '/'      else  '缺失'
     * @purorgid nvarchar(100),        ----采购组织ID
     * @suppreview int,                ----供应商评审天
     * @requirementreview int,                ----需求评审天
     * @LeadTime int,                ----供货周期
     * @Emergency int,                ----紧急采购周期
     * @PreOrderDay int,                ----采购提前期
     * @PurchasingCycle int,                ----采购周期
     * @RefPrice decimal(18, 2),        ----参考价格
     * @AnnualDemand decimal(18, 2),        ----年需求量
     * @DailyDemand decimal(18, 2),        ----日需求量
     * @CostOfOrder decimal(18, 2),        ----订货成本
     * @OrderApportionment decimal(10, 2),    ----订货占比
     * @AnnualCost decimal(10, 2),        ----年化资金成本
     * @StoreCost decimal(10, 2),        ----存储成本
     * @MinInventory decimal(10, 2),        ----最低库存
     * @SafeInventory decimal(10, 2),        ----安全库存
     * @MaxInventory decimal(10, 2),        ----最高库存
     * @EconomicOrder int,                ----经济订货次数
     * @IsStore nvarchar(10),        ----库存管理    1  是   0  否
     * @AllowNegative nvarchar(10),        ----负库存	 1  是   0  否
     * @Batch nvarchar(10),        ----批次管理	 1  是   0  否
     * @auditor nvarchar(100)        ----审批人  02.0100 张三
     */
    private void callProcessToPurchase(String bizId) {

        if (StringUtils.isEmpty(bizId)) {
            return;
        }
        //编写sql
        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.COMPANY_MATERIALS);
        StringBuilder sql = new StringBuilder("SELECT * from ")
                .append(tableName).append(" where id ='")
                .append(bizId).append("';");
        //查询到入参
        Map<String, Object> map = sqlService.getMap(sql.toString());

        log.info("入参map={}", map);

        //调用存储过程
        String company = MapUtils.getString(map, "company", "");//公司id
        String fullCodeNumber = MapUtils.getString(map, "fullCodeNumber", "");//物料代码
        String companyPurchase = MapUtils.getString(map, "companyPurchase", "");//公司采购
        String purchasePostNumber = MapUtils.getString(map, "purchasePostNumber", "");//公司采购岗代码
        String supplier = MapUtils.getString(map, "supplier", "");//主供应商ID（即公司往来单位的编码）
        String purchasingUnit = MapUtils.getString(map, "purchasingUnit", "");//采购计量单位名称
        String purchasingMethod = MapUtils.getString(map, "purchasingMethod", "");//采购方式  	 'group' then '集团'    'company'  '公司'   else  '' end  as 采购方式,
        String purchasingMethodValue = "else";
        switch (purchasingMethod) {
            case "集团":
                purchasingMethodValue = "group";
                break;
            case "公司":
                purchasingMethodValue = "company";
                break;
        }

        String purchasingLevel = MapUtils.getString(map, "purchasingLevel", "");//采购等级(采购级别)  '1'  I级   '2'  Ⅱ级  '3'  Ⅲ级    '0'  '/'      else  '缺失'
        String purchasingLevelValue = new String();
        switch (purchasingLevel) {
            case "Ⅰ":
                purchasingLevelValue = "1";
                break;
            case "Ⅱ":
                purchasingLevelValue = "2";
                break;
            case "Ⅲ":
                purchasingLevelValue = "3";
                break;
            case "/":
                purchasingLevelValue = "0";
                break;
            case "缺失":
                purchasingLevelValue = "";
                break;
        }

        String purchasingOrg = MapUtils.getString(map, "purchasingOrg", "");//采购组织ID(指定采购组织)
        Integer supplierReview = MapUtils.getInteger(map, "supplierReview", 0);


        Integer requirementReview = MapUtils.getInteger(map, "requirementReview", 0);//需求评审天
        Integer supplyCycle = MapUtils.getInteger(map, "supplyCycle", 0);//供货周期
        Integer urgentProcurementCycle = MapUtils.getInteger(map, "urgentProcurementCycle", 0);//紧急采购周期
        Integer plannedOrderLeadTime = MapUtils.getInteger(map, "plannedOrderLeadTime", 0);//采购提前期  计划订货提前期（天）
        Integer procurementCycle = MapUtils.getInteger(map, "procurementCycle", 0);//采购周期

        String referenceUnitPrice = transitionBigDecimal((BigDecimal) map.get("referenceUnitPrice"), 2);//参考价格
        String annualDemand = transitionBigDecimal((BigDecimal) map.get("annualDemand"), 2);//年需求量
        String dailyDemand = transitionBigDecimal((BigDecimal) map.get("dailyDemand"), 2);//日需求量
        String orderCost = transitionBigDecimal((BigDecimal) map.get("orderCost"), 2);//订货成本
        String orderProportion = transitionBigDecimal((BigDecimal) map.get("orderProportion"), 2);//订货占比
        String annualizedCapitalCost = transitionBigDecimal((BigDecimal) map.get("annualizedCapitalCost"), 2);//年化资金成本
        String variableStorageCost = transitionBigDecimal((BigDecimal) map.get("variableStorageCost"), 2);//存储成本
        String minimumStock = transitionBigDecimal((BigDecimal) map.get("minimumStock"), 2);//最低库存
        String safetyStock = transitionBigDecimal((BigDecimal) map.get("safetyStock"), 2);//安全库存
        String maximumStock = transitionBigDecimal((BigDecimal) map.get("maximumStock"), 2);//最高库存
        String economicOrderTimes = transitionBigDecimal((BigDecimal) map.get("economicOrderTimes"), 2);//经济订货次数
        String stockManagement = "√".equalsIgnoreCase(MapUtils.getString(map, "stockManagement", "")) ? "1" : "0";//库存管理    1  是   0  否
        String allowNegativeStock = "√".equalsIgnoreCase(MapUtils.getString(map, "allowNegativeStock", "")) ? "1" : "0";//负库存	 1  是   0  否
        String batchManagement = "√".equalsIgnoreCase(MapUtils.getString(map, "batchManagement", "")) ? "1" : "0";//批次管理	 1  是   0  否
        String approver = MapUtils.getString(map, "approver", "");//审批人  02.0100 张三


        String execSql = String.format("exec [HG_LINK].[hg].[dbo].SyncComMatPurchaseInfo '%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s'",
                company, fullCodeNumber, companyPurchase, purchasePostNumber, supplier,
                purchasingUnit, purchasingMethodValue, purchasingLevelValue, purchasingOrg, supplierReview,
                requirementReview, supplyCycle, urgentProcurementCycle, plannedOrderLeadTime, procurementCycle,
                referenceUnitPrice, annualDemand, dailyDemand, orderCost, orderProportion,
                annualizedCapitalCost, variableStorageCost, minimumStock, safetyStock, maximumStock,
                economicOrderTimes, stockManagement, allowNegativeStock, batchManagement, approver);

        log.info("\n==========准备调用[SyncComMatPurchaseInfo]公司物料信息记录 采购信息 存储过程:{}", execSql);
        sqlService.execute(CloudSqlService.htEas, execSql);
        log.info("\n=============[SyncComMatPurchaseInfo]公司物料信息记录 采购信息 存储过程执行完成");

    }

    private String transitionBigDecimal(BigDecimal bigDecimal, int flag) {
        String actualPriceStr = bigDecimal == null ? "0" : bigDecimal.toString();//获取子表数据 现价
        BigDecimal actualPrice = "0E-8".equals(actualPriceStr) ? new BigDecimal("0") : new BigDecimal(actualPriceStr).setScale(flag, BigDecimal.ROUND_HALF_UP);
        return actualPrice.toString();
    }

    /**
     * 更新公司物料信息-销售信息
     */
    @RequestMapping("updateCompanyMaterialsSale")
    public void updateCompanyMaterialsSale(String bizId) {
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.COMPANY_MATERIALS_SA, bizId);
        List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get(CustomSchemaCode.COMPANY_MATERIALS_DETAIL_SA);
        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        String approval = getFileBaseInfoWorkFlowApproval(bizObject);
        String tableName = this.getBizObjectFacade().getTableName(CustomSchemaCode.COMPANY_MATERIALS);
        for (Map<String, Object> map : list) {
            try {
                //获取参数
                String companyNumber = MapUtils.getString(map, "companyNumber", "");//公司
                String fullCodeNumber = MapUtils.getString(map, "fullCodeNumber", "");//编号
                String companySales = MapUtils.getString(map, "companySales", "");//公司销售
                // 销售岗是关联单选，需要获取id
                Map<String, Object> salePostMap = (Map<String, Object>) map.get("salePost");
                String salePostId = String.valueOf(salePostMap.get("id"));
                String salePostNumber = MapUtils.getString(map, "salePostNumber", "");//销售岗代码隐藏
                String saleMethod = MapUtils.getString(map, "saleMethod", "");//销售方式
                String saleUnit = MapUtils.getString(map, "saleUnit", "");//销售计量单位
                Map<String, Object> relevanceSaleUnitMap = (Map<String, Object>) map.get("relevanceSaleUnit");
                String relevanceSaleUnit = MapUtils.isNotEmpty(relevanceSaleUnitMap) ? relevanceSaleUnitMap.get("id").toString() : "";
                StringBuilder sql = new StringBuilder();
                sql.append("update ").append(tableName)
                        .append(" set companySales = '").append(companySales).append("'")
                        .append(",salePost = '").append(salePostId).append("'")
                        .append(",salePostNumber = '").append(salePostNumber).append("'")
                        .append(",saleMethod = '").append(saleMethod).append("'")
                        .append(",saleUnit = '").append(saleUnit).append("'")
                        .append(",relevanceSaleUnit = '").append(relevanceSaleUnit).append("'")
                        .append(",auditDate = '").append(now).append("'")
                        .append(",approver = '").append(approval).append("'")
                        .append(" where fullCodeNumber = '").append(fullCodeNumber).append("'")
                        .append(" and companyNumber = '").append(companyNumber).append("'");
                sqlService.update(sql.toString());
                log.info("公司物料信息记录 销售信息数据修改成功");

                callProcessToSale(fullCodeNumber,companyNumber);
            } catch (Exception e) {
                log.info("公司物料信息记录 销售信息数据维护失败，报错信息：{}", e.getMessage());
                log.info("公司物料信息记录 销售信息操作失败 公司编码={}，物料编码={}", map.get("companyNumber"), map.get("fullCodeNumber"));
            }
        }
    }

    /**
     * ------公司物料信息 销售信息
     * exec   SyncComMatSaleInfo
     *
     * @comid nvarchar(100),            -----公司id
     * @code nvarchar(100),            -----物料代码
     * @SaleArch nvarchar(100),            ----销售档案
     * @SaleType nvarchar(10),            ----销售类型
     * @SaleUnitName nvarchar(100),            ----销售计量单位名称  个  只
     * @SalePosCode nvarchar(100),            ----销售岗代码
     * @auditor nvarchar(100)        ----审批人  02.0100 张三
     */
    private void callProcessToSale(String fullCodeNumber, String companyNumber) {

        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.COMPANY_MATERIALS);

        StringBuilder sql = new StringBuilder("select id  from ").append(tableName)
                .append(" where fullCodeNumber='").append(fullCodeNumber).append("'")
                .append(" and companyNumber='").append(companyNumber).append("'")
                .append(";");
        Map<String, Object> map = sqlService.getMap(sql.toString());
        String bizId = (String) map.get("id");
        if (StringUtils.isEmpty(bizId)) {
            return;
        }
        log.info("入参map={}", map);

        String company = MapUtils.getString(map, "company", "");//公司id
//        String fullCodeNumber = MapUtils.getString(map, "fullCodeNumber", "");//物料代码
        String companySales = MapUtils.getString(map, "companySales", "");//销售档案
        String saleMethod = MapUtils.getString(map, "saleMethod", "");//销售类型
        String saleMethodValue = "else";
        switch (saleMethod) {
            case "集团":
                saleMethodValue = "group";
                break;
            case "公司":
                saleMethodValue = "company";
                break;
        }

        String saleUnit = MapUtils.getString(map, "saleUnit", "");//销售计量单位名称  个  只
        String salePostNumber = MapUtils.getString(map, "salePostNumber", "");//销售岗代码
        String approver = MapUtils.getString(map, "approver", "");//审批人  02.0100 张三

        String execSql = String.format("exec [HG_LINK].[hg].[dbo].SyncComMatSaleInfo '%s','%s'",
                company, fullCodeNumber, companySales, saleMethodValue, saleUnit, salePostNumber, approver);
        log.info("\n==========准备调用[SyncComMatSaleInfo] 公司物料信息 销售信息 存储过程:{}", execSql);
        sqlService.execute(CloudSqlService.htEas, execSql);
        log.info("\n=============[SyncComMatSaleInfo] 公司物料信息 销售信息 存储过程执行完成");
    }

//    @RequestMapping("toVoid")
//    public void toVoid(String bizId) {
//        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.COMPANY_MATERIALS_VOID, bizId);
//        List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get(CustomSchemaCode.COMPANY_MATERIALS_DETAIL_VOID);
//
//        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
//
//        //获取审批人
//        String approval = getFileBaseInfoWorkFlowApproval(bizObject);
//
//        for (Map<String, Object> map : list) {
//            try {
//                //获取数据
//                Map<String, Object> data = Utils.fileInfoBaseMap(map, approval);
//                //判断是否已存在
//                String id = existsBizObject(map);
//                if (StringUtils.isEmpty(id)) {
//                    //判断是否已存在，如果不存在，放弃这条数据，直接跳过此次循环
//                    continue;
//                } else if (StringUtils.isNotEmpty(id)) {
//                    data.put("id", id);
//                }
//
//                BizObjectCreatedModel model = new BizObjectCreatedModel(CustomSchemaCode.COMPANY_MATERIALS, data, false);
//                model.setSequenceStatus(SequenceStatus.CANCELED.name());
//                id = getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
//                log.info("公司物料信息记录 基础表作废操作成功");
//                //调用存储过程
//                callProcessToVoid(id);
//            } catch (Exception e) {
//                log.error(e.getMessage(), e);
//                log.info("公司物料信息记录 作废失败 公司编码={}，物料编码={}", map.get("companyNumber"), map.get("fullCodeNumber"));
//            }
//        }
//    }
//
//    /**
//     * 调用作废存储过程
//     * --------公司物料信息记录 作废
//     * exec    CorpMaterialDisAble
//     */
//    private void callProcessToVoid(String bizId) {
//
//        if (StringUtils.isEmpty(bizId)) {
//            return;
//        }
//        //编写sql
//        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.HEAD_OFFICE_MATERIALS);
//        StringBuilder sql = new StringBuilder("SELECT * from ")
//                .append(tableName).append(" where id ='")
//                .append(bizId).append("';");
//        //查询到入参
//        Map<String, Object> map = sqlService.getMap(sql.toString());
//
//        log.info("入参map={}", map);
//
//        //调用存储过程
//        String fullCodeNumber = MapUtils.getString(map, "fullCodeNumber", "");//公司fid
//
//        String execSql = String.format("exec [HG_LINK].[hg].[dbo].CorpMaterialDisAble '%s'",
//                fullCodeNumber);
//
//        log.info("\n==========准备调用作废存储过程:{}", execSql);
//
//        sqlService.execute(CloudSqlService.htEas, execSql);
//
//        log.info("\n=============作废存储过程执行完成");
//
//    }

    /**
     * 查询审批人,返回  员工号+姓名
     *
     * @param bizObject
     * @return
     */
    private String getFileBaseInfoWorkFlowApproval(BizObjectCreatedModel bizObject) {
        WorkflowInstanceModel instanceModel = getWorkflowInstanceFacade().getByObjectId(bizObject.getId());
        List<WorkItemModel> workItems = getWorkflowInstanceFacade().getWorkItems(instanceModel.getId(), true);
        final String finalActivityCode = "Activity21";
        Optional<WorkItemModel> first = workItems.stream().filter(a -> a.getActivityCode().equals(finalActivityCode)).findFirst();
        String participant = null;
        if (first.isPresent()) {
            WorkItemModel workItemModel = first.get();
            participant = workItemModel.getParticipant();
        }
        if (participant == null) {
            final String finalActivityCode2 = "Activity18";
            Optional<WorkItemModel> second = workItems.stream().filter(a -> a.getActivityCode().equals(finalActivityCode2)).findFirst();
            if (second.isPresent()) {
                WorkItemModel workItemModel = second.get();
                participant = workItemModel.getParticipant();
            }
        }

        if (participant == null) {
            participant = bizObject.getCreater().getId();
        }

        UserModel user = getOrganizationFacade().getUser(participant);


        return new StringBuilder(user.getEmployeeNo()).append("　").append(user.getName()).toString();
    }


    /**
     * 判断是否已存在
     *
     * @return
     */
    private String existsBizObject(Map data) {

        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.COMPANY_MATERIALS);

        StringBuilder sql = new StringBuilder("select id  from ").append(tableName)
                .append(" where fullCodeNumber='").append(data.get("fullCodeNumber")).append("'")
                .append(" and companyNumber='").append(data.get("companyNumber")).append("'")
                .append(";");
        Map<String, Object> map = sqlService.getMap(sql.toString());
        return (String) map.get("id");
    }

    /**
     * 转换成  基础表-公司档案 的数据
     *
     * @param map
     * @param auditDate
     * @return
     */
    private Map<String, Object> fileInfoBaseMap(Map<String, Object> map, String auditDate, String auditer) {
        Map<String, Object> data = new HashMap<>();
        List<String> keys = Arrays.asList("fullCodeNumber", "sinopecName", "materialName", "materialAlias", "materialForeignName", "modelExample", "mnemonicCode",
                "unitPricePrecision", "unitPrecision", "assistUnitPrecision", "materialStatus", "companyDutyDeptFNumber", "companyPostANumber", "companyPostBNumber",
                "image", "headOfficeStandard", "headOfficePurchase", "headOfficeSales", "companyStandard", "companyNumber");
        // 子表id
        data.put("childTableID", map.get("id"));
        keys.forEach(key -> data.put(key, map.get(key)));
        // 主责人
        data.put("CompanyPersonName", map.get("companyDutyPerson"));
        List<String> relationKeys = Arrays.asList("company", "companyDutyDeptFid", "companyPostA", "companyPostB", "baseMeasureUnit", "assistMeasureUnit",
                "mainCompany", "responsibleDeptFid", "relevancePost");
        relationKeys.forEach(key -> {
            Map<String, Object> relationMap = (Map<String, Object>) map.get(key);
            data.put(key, relationMap.get("id"));
        });
        //审批时间和审批人
        data.put("auditDate", auditDate);
        data.put("approver", auditer);
        return data;
    }

    /**
     * 公司采购信息转换成  基础表-公司档案 的数据
     *
     * @param map
     * @param auditDate
     * @return
     */
    private Map<String, Object> fileInfoPurchaseMap(Map<String, Object> map, String auditDate, String auditer) {
        Map<String, Object> data = new HashMap<>();
        List<String> keys = Arrays.asList("companyPurchase", "purchasePostNumber", "supplier", "purchasingUnit", "purchasingOrgNumber", "purchasingMethod", "purchasingLevel",
                "requirementReview", "supplierReview", "supplyCycle", "urgentProcurementCycle", "plannedOrderLeadTime", "procurementCycle", "referenceUnitPrice",
                "annualDemand", "dailyDemand", "orderCost", "orderProportion", "annualizedCapitalCost", "variableStorageCost", "minimumStock",
                "safetyStock", "maximumStock", "economicOrderTimes", "stockManagement", "allowNegativeStock", "batchManagement");
        // 子表id
        data.put("childTableID", map.get("id"));
        keys.forEach(key -> data.put(key, map.get(key)));
        List<String> relationKeys = Arrays.asList("purchasePost", "purchasingOrg", "relevancePurchasingUnit");
        relationKeys.forEach(key -> {
            Map<String, Object> relationMap = (Map<String, Object>) map.get(key);
            data.put(key, relationMap.get("id"));
        });
        //审批时间和审批人
        data.put("auditDate", auditDate);
        data.put("approver", auditer);
        return data;
    }
}
